package com.fingard.dsp.bank.directbank.baofoo01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.directbank.baofoo01.util.FormatUtil;
import com.fingard.dsp.bank.directbank.baofoo01.util.RsaCodingUtil;
import com.fingard.dsp.bank.directbank.baofoo01.util.SecurityUtil;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.io.FileHelper;

import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

public class BaoFoo01Contract extends BaoFoo01Base implements IContract {
    @Override
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.contractDetail.recAct, "contract");
            if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
                if (actItem == null) {
                    throw new Exception("未找到账号" + p_req.contractDetail.recAct + "对应的商户配置信息");
                } else {
                    throw new Exception("账号" + p_req.contractDetail.recAct + "对应的证书文件不存在");
                }
            }
            Map<String,String> postParams = new TreeMap<String,String>();
            postParams.put("send_time", Format.DateTimeFormat.format(new Date()));
            postParams.put("msg_id", getQryTransID());
            postParams.put("version", "4.0.0.0");
            postParams.put("terminal_id", actItem.termId);
            postParams.put("member_id", actItem.merchantId);
            String dgtl_envlp = "01|"+actItem.saltKey;
            dgtl_envlp = RsaCodingUtil.encryptByPubCerFile(SecurityUtil.Base64Encode(dgtl_envlp), actItem.oppCertFilePath);//公钥加密
            postParams.put("dgtl_envlp", dgtl_envlp);
            if ("01".equals(p_req.contractDetail.step)) {
                String filter = "|";
                String cardinfo = p_req.contractDetail.payAct+filter+p_req.contractDetail.payName+filter+p_req.contractDetail.certNum+filter+p_req.contractDetail.cellPhone+filter+filter;
                WriteBankLogLn("加密前的Cardinfo=" + cardinfo);
                WriteBankLogLn("SHA-1摘要[Cardinfo]结果："+SecurityUtil.sha1X16(cardinfo, "UTF-8"));
                WriteBankLogLn("卡信息："+cardinfo+",长度："+cardinfo.length());
                cardinfo = SecurityUtil.AesEncrypt(SecurityUtil.Base64Encode(cardinfo), actItem.saltKey);//先BASE64后进行AES加密
                WriteBankLogLn("AES结果:"+cardinfo);
                String cardType = p_req.contractDetail.cardType;
                if ("3".equals(cardType) || "4".equals(cardType)) {
                    cardType = "102";// 信用卡
                } else {
                    cardType = "101";// 借记卡(默认)
                }
                postParams.put("txn_type", "01");
                postParams.put("card_type", cardType);
                postParams.put("id_card_type", "01");
                postParams.put("member_id", actItem.merchantId);
                postParams.put("acc_info", cardinfo);
            } else if ("02".equals(p_req.contractDetail.step)) {
                String unique_code = p_req.contractDetail.token+"|"+p_req.contractDetail.smsCode;
                WriteBankLogLn("预签约唯一码："+unique_code);
                unique_code = SecurityUtil.AesEncrypt(SecurityUtil.Base64Encode(unique_code), actItem.saltKey);//先BASE64后进行AES加密
                postParams.put("unique_code", unique_code);
                postParams.put("txn_type", "02");
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未能识别的step：" + p_req.contractDetail.step;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            postParams.put("signature", sign(postParams,actItem));

            String[] tmpStrRet = sendToBank("contract",postParams,actItem);

            if (tmpStrRet[0].length() == 0) {
                Map<String, String> ReturnData = FormatUtil.getParm(tmpStrRet[1]);
                String resp_code = ReturnData.get("resp_code");
                String biz_resp_code = ReturnData.get("biz_resp_code");
                if("S".equals(resp_code)){
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = ReturnData.get("biz_resp_msg");
                    String RDgtlEnvlp = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPriPfxFile(ReturnData.get("dgtl_envlp"), actItem.ownKeyStorePath, actItem.ownKeyPassword));
                    WriteBankLogLn("返回数字信封："+RDgtlEnvlp);
                    String RAesKey=FormatUtil.getAesKey(RDgtlEnvlp);//获取返回的AESkey
                    if("01".equals(p_req.contractDetail.step)) {
                        tmpRetDetail.token = SecurityUtil.Base64Decode(SecurityUtil.AesDecrypt(ReturnData.get("unique_code"),RAesKey));
                    }else {
                        if("0000".equals(biz_resp_code)){
                            tmpRetDetail.signState = ContractState.SUCCESS;
                            tmpRetDetail.authCode = SecurityUtil.Base64Decode(SecurityUtil.AesDecrypt(ReturnData.get("protocol_no"),RAesKey));
                        }else {
                            tmpRetDetail.signState = ContractState.FAIL;
                        }
                    }
                    tmpRetDetail.signConfirmType = "2";
                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", biz_resp_code);
                }else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = ReturnData.get("biz_resp_msg");
                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", biz_resp_code);
                }

            } else {
                Map<String, String> ReturnData = FormatUtil.getParm(tmpStrRet[1]);
                String resp_code = ReturnData.get("biz_resp_msg");
                String biz_resp_code = ReturnData.get("biz_resp_code");
                tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", biz_resp_code);
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = resp_code;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;
        try{
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQry.contractDetail.recAct, "contract");
            if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
                if (actItem == null) {
                    throw new Exception("未找到账号" + p_reqQry.contractDetail.recAct + "对应的商户配置信息");
                } else {
                    throw new Exception("账号" + p_reqQry.contractDetail.recAct + "对应的证书文件不存在");
                }
            }
            Map<String,String> postParams = new TreeMap<String,String>();
            postParams.put("send_time", Format.DateTimeFormat.format(new Date()));
            postParams.put("msg_id", p_reqQry.contractDetail.askNumber);
            postParams.put("version", "4.0.0.0");
            postParams.put("terminal_id", actItem.termId);
            postParams.put("txn_type", "03");
            postParams.put("member_id", actItem.merchantId);
            String dgtl_envlp = "01|"+actItem.saltKey;
            dgtl_envlp = RsaCodingUtil.encryptByPubCerFile(SecurityUtil.Base64Encode(dgtl_envlp), actItem.oppCertFilePath);//公钥加密
            postParams.put("dgtl_envlp", dgtl_envlp);
            String AccNo = SecurityUtil.AesEncrypt(SecurityUtil.Base64Encode(p_reqQry.contractDetail.payAct), actItem.saltKey);//先BASE64后进行AES加密
            postParams.put("acc_no", AccNo);
            postParams.put("signature", sign(postParams,actItem));
            String[] tmpStrRet = sendToBank("contract",postParams,actItem);

            if (tmpStrRet[0].length() == 0) {
                Map<String, String> ReturnData = FormatUtil.getParm(tmpStrRet[1]);
                String resp_code = ReturnData.get("resp_code");
                String biz_resp_code = ReturnData.get("biz_resp_code");
                if("S".equals(resp_code)){
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = ReturnData.get("biz_resp_msg");
                    if("0000".equals(biz_resp_code)){
                        tmpRetDetail.signState = ContractState.SUCCESS;
                    }else {
                        tmpRetDetail.signState = ContractState.FAIL;
                    }
                    if (ContractState.SUCCESS.equals(tmpRetDetail.signState)) {
                        String RDgtlEnvlp = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPriPfxFile(ReturnData.get("dgtl_envlp"), actItem.ownKeyStorePath, actItem.ownKeyPassword));
                        WriteBankLogLn("返回数字信封："+RDgtlEnvlp);
                        String RAesKey=FormatUtil.getAesKey(RDgtlEnvlp);//获取返回的AESkey
                        WriteBankLogLn("返回的AESkey:"+RAesKey);
                        String protocols = SecurityUtil.Base64Decode(SecurityUtil.AesDecrypt(ReturnData.get("protocols"),RAesKey));
                        WriteBankLogLn("协议列表:"+protocols);
                        String[] splits = protocols.split("\\|");
                        tmpRetDetail.authCode = splits[0];
                        tmpRetDetail.payAct =p_reqQry.contractDetail.payAct;
                        tmpRetDetail.signConfirmType = "2";
                    }
                }else {
                    if("BF00134".equals(biz_resp_code)){
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.signState = ContractState.UNSIGNED;
                        tmpRetDetail.respInfo ="未签约";
                    }else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = ReturnData.get("biz_resp_msg");
                    }

                }

            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        }catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}
